﻿<%@ WebHandler Language="C#" Class="Web.API.index" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;
using System.IO;
using System.Text;

using Common;
using System.Xml;

namespace Smy.Web.API
{
    public class APP
    {
        public APP()
        {
            string fullPath = Utils.GetXmlMapPath("AppPath");
            XmlDocument doc = new XmlDocument();
            doc.Load(fullPath);

            app_key = doc.SelectSingleNode(@"App/app_key").InnerText;
            app_name = doc.SelectSingleNode(@"App/app_name").InnerText;
        }

        public string app_name { get; set; }
        public string app_key { get; set; }
    }

    /// <summary>
    /// index 的摘要说明
    /// </summary>
    public class index : IHttpHandler, IRequiresSessionState
    {
        APP app = new APP();

        public void ProcessRequest(HttpContext context)
        {
            string action = STRequest.GetString("action");
            string method = STRequest.GetString("method");
            string appName = STRequest.GetString("app_name");
            string appKey = STRequest.GetString("app_key");

            string serverIP = STRequest.GetString("ip");
            string hostName = STRequest.GetString("host");

            string currentIP = HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"];
            string currentHost = STRequest.GetDnsSafeHost();

            if (serverIP != currentIP || hostName != currentHost)
            {
                context.Response.Write("{\"status:0\",\"info\":\"IP/域名错误\"}");
                return;
            }


            if (!"method".Equals(action))
            {
                context.Response.Write("{\"status:0\",\"info\":\"调用方法错误\"}");
                return;
            }

            if (app.app_key != appKey || app.app_name != appName)
            {
                context.Response.Write("{\"status:0\",\"info\":\"APP参数错误\"}");
                return;
            }

            switch (method)
            {
                case "manager_login":
                    manager_login(context);
                    break;
                case "manager_update_info":
                    manager_update_info(context);
                    break;
                case "manager_reset_pwd":
                    manager_reset_pwd(context);
                    break;
                case "manager_list":
                    manager_list(context);
                    break;
                case "manager_model":
                    manager_model(context);
                    break;
                case "manager_add":
                    manager_add(context);
                    break;
                case "manager_validate":
                    manager_validate(context);
                    break;
                case "manager_delete":
                    manager_delete(context);
                    break;
                default:
                    context.Response.Write("{\"status:0\",\"info\":\"调用方法错误\"}");
                    break;
            }
            context.Response.End();
        }

        private void manager_delete(HttpContext context)
        {
            int id = STRequest.GetInt("id", 0);
            BLL.Manager bll = new BLL.Manager();
            if (bll.Delete(id))
            {
                context.Response.Write("{ \"info\":\"删除管理员成功\", \"status\":\"1\" }");
                return;
            }
            context.Response.Write("{ \"info\":\"删除管理员错误\", \"status\":\"0\" }");
        }

        private void manager_validate(HttpContext context)
        {
            string user_name = STRequest.GetString("param");
            if (string.IsNullOrEmpty(user_name))
            {
                context.Response.Write("{ \"info\":\"请输入用户名\", \"status\":\"0\" }");
                return;
            }
            BLL.Manager bll = new BLL.Manager();
            if (bll.Exists(user_name))
            {
                context.Response.Write("{ \"info\":\"用户名已被占用，请更换！\", \"status\":\"0\" }");
                return;
            }
            context.Response.Write("{ \"info\":\"用户名可使用\", \"status\":\"1\" }");
            return;
        }

        private void manager_add(HttpContext context)
        {
            string user_name = STRequest.GetString("user_name");
            string email = STRequest.GetString("email");
            int is_lock = STRequest.GetInt("is_lock", 0);
            string password = STRequest.GetString("password");
            string real_name = STRequest.GetString("real_name");
            int role_id = STRequest.GetInt("role_id", 0);
            string salt = Utils.GetCheckCode(6);
            string telephone = STRequest.GetString("telephone");

            password = DESEncrypt.Encrypt(password, salt);

            Model.Manager model = new Model.Manager();
            model.email = email;
            model.is_lock = is_lock;
            model.password = password;
            model.real_name = real_name;
            model.role_id = role_id;
            model.role_type = role_id;
            model.salt = salt;
            model.telephone = telephone;
            model.add_time = DateTime.Now;
            model.user_name = user_name;
            BLL.Manager bll = new BLL.Manager();
            if (bll.Add(model) > 0)
            {
                new BLL.ManagerLog().Add(0, "", STEnums.ActionEnum.Add.ToString(), "远程添加管理员:" + model.user_name); //记录日志
                context.Response.Write("{\"status\":1,\"info\":\"添加管理员成功\"}");
            }
            else
            {

                context.Response.Write("{\"status\":0,\"info\":\"添加管理员失败\"}");

            }
        }

        private void manager_model(HttpContext context)
        {
            int id = STRequest.GetInt("id", 0);
            Model.Manager model = new BLL.Manager().GetModel(id);
            Hashtable hs = new Hashtable();
            hs["model"] = model;
            if (model != null)
            {
                hs["status"] = 1;
            }
            else
            {
                hs["status"] = 0;
            }
            context.Response.Write(JsonHelper.ObjectToJSON(hs));
        }

        private void manager_list(HttpContext context)
        {
            BLL.Manager bll = new BLL.Manager();

            int pageSize = STRequest.GetInt("size", 10);
            int page = STRequest.GetInt("page", 1);
            string strWhere = STRequest.GetString("where");
            string orderby = STRequest.GetString("orderby");

            int totalcount = 0;
            DataTable dt = bll.GetList(pageSize, page, strWhere, orderby, out totalcount).Tables[0];

            List<Dictionary<string, object>> listDic = JsonHelper.DataTableToList(dt);

            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("count", totalcount);
            dic.Add("list", listDic);
            context.Response.Write(JsonHelper.ObjectToJSON(dic));
        }

        private void manager_reset_pwd(HttpContext context)
        {
            BLL.Manager bll = new BLL.Manager();
            DataSet ds=bll.GetList(1,"user_name='admin'","id desc");

            if (ds.Tables[0].Rows.Count>0)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                Model.Manager model = new Model.Manager();
                model.add_time = Utils.ObjectToDateTime(dr["add_time"]);
                model.email = dr["email"].ToString();
                model.id = Utils.ObjToInt(dr["id"], 0);
                model.is_lock = Utils.ObjToInt(dr["is_lock"], 0);
                model.real_name = dr["real_name"].ToString();
                model.role_id = Utils.ObjToInt(dr["role_id"], 0);
                model.role_type = Utils.ObjToInt(dr["role_type"], 0);
                model.salt = dr["salt"].ToString();
                model.telephone = dr["telephone"].ToString();
                model.user_name = dr["user_name"].ToString();
                string newpwd = Utils.GetCheckCode(6);
                
                model.password = DESEncrypt.Encrypt(newpwd, model.salt);
                
                
                if (bll.Update(model))
                {
                    context.Response.Write("{\"status\":1,\"info\":\"密码重置成功！\",\"pwd\":\"" + newpwd + "\",\"salt\":\""+model.salt+"\"}");
                }
                else
                {
                    context.Response.Write("{\"status\":0,\"info\":\"密码重置失败！\"}");
                }
            }
            else
            {
                context.Response.Write("{\"status\":0,\"info\":\"密码重置失败！\"}");
            }

        }

        private void manager_update_info(HttpContext context)
        {
            string strManagerJSON = STRequest.GetString("model");
            strManagerJSON = strManagerJSON.Replace(@"\", "");
            BLL.Manager bll = new BLL.Manager();


            Dictionary<string, object> dic = JsonHelper.DataRowFromJSON(strManagerJSON);
            if (dic == null)
            {
                context.Response.Write("{\"status\":0,\"info\":\"修改管理员失败！\"}");
                return;
            }
            Model.Manager model = bll.GetModel(Utils.ObjToInt(dic["id"], 0));

            model.email = dic["email"].ToString();
            model.id = Utils.ObjToInt(dic["id"], 0);
            model.is_lock = Utils.ObjToInt(dic["is_lock"], 0);
            model.password = dic["password"].ToString();
            model.real_name = dic["real_name"].ToString();
            model.role_id = Utils.ObjToInt(dic["role_id"], 0);
            model.role_type = Utils.ObjToInt(dic["role_type"], 0);
            model.salt = dic["salt"].ToString();
            model.telephone = dic["telephone"].ToString();

            if (bll.Update(model))
            {
                new BLL.ManagerLog().Add(model.id, model.user_name, STEnums.ActionEnum.Edit.ToString(), "修改管理员信息");
                context.Response.Write("{\"status\":1,\"info\":\"修改管理员信息！\"}");
            }
        }

        private void manager_login(HttpContext context)
        {
            string state = STRequest.GetString("state");
            Utils.WriteCookie("state", state);
            Model.Manager model = new Model.Manager();
            BLL.Manager bll = new BLL.Manager();
            DataSet ds = bll.GetList(1, "user_name='admin'", "id desc");

            if (ds.Tables[0].Rows.Count > 0)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                model.add_time = Utils.ObjectToDateTime(dr["add_time"]);
                model.email = dr["email"].ToString();
                model.id = Utils.ObjToInt(dr["id"], 0);
                model.is_lock = Utils.ObjToInt(dr["is_lock"], 0);
                model.real_name = dr["real_name"].ToString();
                model.role_id = Utils.ObjToInt(dr["role_id"], 0);
                model.role_type = Utils.ObjToInt(dr["role_type"], 0);

                model.salt = dr["salt"].ToString();
                model.telephone = dr["telephone"].ToString();
                model.user_name = dr["user_name"].ToString();
                model.password = dr["password"].ToString();
            }

            if (model == null)
            {
                context.Response.Write("{\"status\":0,\"info\":\"用户名或密码有误，请重试！\"}");
                return;
            }
            
            
            
            context.Session[STKeys.SESSION_ADMIN_INFO] = model;
            context.Session.Timeout = 45;
            //写入登录日志
            Model.SystemConfig config = new BLL.SystemConfig().loadConfig();
            if (config.logstatus > 0)
            {
                new BLL.ManagerLog().Add(model.id, model.user_name, STEnums.ActionEnum.Login.ToString(), "用户登录");
            }
            //写入Cookies
            Utils.WriteCookie("AdminName", "Smy", model.user_name);
            Utils.WriteCookie("AdminPwd", "Smy", model.password);

            context.Response.Redirect(config.webpath + config.webmanagepath + "/index.aspx");

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }


    public class JsonHelper
    {
        public JsonHelper() { }

        /// <summary>
        /// 把对象序列化 JSON 字符串 
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">对象实体</param>
        /// <returns>JSON字符串</returns>
        public static string GetJson<T>(T obj)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                json.WriteObject(ms, obj);
                string szJson = Encoding.UTF8.GetString(ms.ToArray());
                return szJson;
            }
        }
        /// <summary>
        /// 把JSON字符串还原为对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="szJson">JSON字符串</param>
        /// <returns>对象实体</returns>
        public static T ParseFormJson<T>(string szJson)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
                DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
                return (T)dcj.ReadObject(ms);
            }
        }

        /// <summary> 
        /// 对象转JSON 
        /// </summary> 
        /// <param name="obj">对象</param> 
        /// <returns>JSON格式的字符串</returns> 
        public static string ObjectToJSON(object obj)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                return jss.Serialize(obj);
            }
            catch (Exception ex)
            {
                throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message);
            }
        }


        /// <summary> 
        /// 数据表转键值对集合 
        /// 把DataTable转成 List集合, 存每一行 
        /// 集合中放的是键值对字典,存每一列 
        /// </summary> 
        /// <param name="dt">数据表</param> 
        /// <returns>哈希表数组</returns> 
        public static List<Dictionary<string, object>> DataTableToList(DataTable dt)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    dic.Add(dc.ColumnName, dr[dc.ColumnName]);
                }
                list.Add(dic);
            }
            return list;
        }
        /// <summary> 
        /// 数据集转键值对数组字典 
        /// </summary> 
        /// <param name="dataSet">数据集</param> 
        /// <returns>键值对数组字典</returns> 
        public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds)
        {
            Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>();
            foreach (DataTable dt in ds.Tables)
                result.Add(dt.TableName, DataTableToList(dt));
            return result;
        }
        /// <summary> 
        /// 数据表转JSON 
        /// </summary> 
        /// <param name="dataTable">数据表</param> 
        /// <returns>JSON字符串</returns> 
        public static string DataTableToJSON(DataTable dt)
        {
            return ObjectToJSON(DataTableToList(dt));
        }
        /// <summary> 
        /// JSON文本转对象,泛型方法 
        /// </summary> 
        /// <typeparam name="T">类型</typeparam> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>指定类型的对象</returns> 
        public static T JSONToObject<T>(string jsonText)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                return jss.Deserialize<T>(jsonText);
            }
            catch (Exception ex)
            {
                throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);
            }
        }
        /// <summary> 
        /// 将JSON文本转换为数据表数据 
        /// </summary> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>数据表字典</returns> 
        public static Dictionary<string, List<Dictionary<string, object>>> TablesDataFromJSON(string jsonText)
        {
            return JSONToObject<Dictionary<string, List<Dictionary<string, object>>>>(jsonText);
        }
        /// <summary> 
        /// 将JSON文本转换成数据行 
        /// </summary> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>数据行的字典</returns> 
        public static Dictionary<string, object> DataRowFromJSON(string jsonText)
        {
            return JSONToObject<Dictionary<string, object>>(jsonText);
        }

    }
}